package com.sangen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangen.constants.SystemConstants;
import com.sangen.domin.ResponseResult;
import com.sangen.domin.entity.Article;
import com.sangen.domin.vo.HotArticleVo;
import com.sangen.domin.vo.PageVo;
import com.sangen.mapper.ArticleMapper;
import com.sangen.service.ArticleService;
import com.sangen.utils.BeanCopyUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 文章表(Article)表服务实现类
 *
 * @author makejava
 * @since 2023-04-22 11:11:02
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章 封装为ResponseResult返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //按照浏览量排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多查询10条
        Page<Article> page = new Page<>(1, 10);
        page(page, queryWrapper);

        List<Article> articles = page.getRecords();
//        //bean拷贝
//        List<HotArticleVo> articleVos = new ArrayList<>();
//        for (Article article: articles) {   //将articles集合遍历出来 利用方法拷贝给vo对象
//            HotArticleVo vo = new HotArticleVo();
//            BeanUtils.copyProperties(article,vo);
//            articleVos.add(vo);         //将vo对象存储到articleVos集合中 封装
//        }
        List<HotArticleVo> vs = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);

        return ResponseResult.okResult(vs);
    }

    //查询文章列表
    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件  用queryWrapper封装查询的判断
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        // 1.如果有categoryId 查询时要和传入的相同 此重载方法，当第一个条件成立时，后面的方法才会执行
        queryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0, Article::getCategoryId, categoryId);
        // 2.状态是正式发布的
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        // 3.置顶的文章要显示在最前面 对isTop进行降序
        queryWrapper.orderByDesc(Article::getIsTop);
        //分页查询
        Page<Article> page = new Page<>(pageNum, pageSize); //传入页码 每页大小
        page(page, queryWrapper);
        //封装查询结果
        List<Article> arrayListVos = BeanCopyUtils.copyBeanList(page.getRecords(), Article.class);

        PageVo pageVo = new PageVo(arrayListVos,page.getTotal());


        return ResponseResult.okResult(pageVo);
    }
}

